let userDao = require("../dao/userDao");
let resultUtil = require("../utils/ResultUtils.js");

/**
 * 返回所有用户信息
 * @returns 成功:用户信息对象{code:0,msg:"",count:100,data:{}} 失败:null
 */
async function getAllUsers() { 
  //这里读取的数据，是数据库直接返回的数据
  //但是前端所需要的数据，一般都需要经过处理
  //比如：layui {code:0,msg:"",data:{xxx:xxx}}
  let result = null;
  try {
    let data = await userDao.getAllUsers();
    let count = await userDao.getAllUsersCount();

    result = resultUtil(data, count);
  }
  catch (e) { 
    console.log(e);
  }

  return result;
}

async function list(filter,page=1,limit=10) { 
  let result;
  try {
    //获取集合数据
    let data = await userDao.list(filter, page, limit);
    //获取数量
    let count = await userDao.count(filter);
    
    result = resultUtil(data, count);
  }
  catch (e) { 
    console.log(e);
    result = resultUtil(null,0,-1,"查询出问题了")
  }
  
  return result;
}

async function deleteById(id) {
  let result;
  try {
    let data = await userDao.deleteById(id);
    result = resultUtil(data, 0, 0, "删除成功");
  }
  catch (e) { 
    result = resultUtil(null, 0, -1, "删除失败");
  }
  
  return result;
}

async function add(user) {
  let result;
  try {
    let data = await userDao.add(user);
    result = resultUtil(data, 0, 0, "新增成功");
  }
  catch (e) { 
    result = resultUtil(null, 0, -1, "新增失败");
  }
  
  return result;
}

async function login(loginId,loginPwd) { 
  let result = null;
  try {
    let data = await userDao.login(loginId, loginPwd)
    if (data !== null) {
      result = resultUtil(data, 0, 0, "登录成功");
    }
    else { 
      result = resultUtil(null, 0, -1, "登录失败");
    }
    
  }
  catch (e) { 
    result = resultUtil(null, 0,-1,"登录失败,用户名或者密码错误");
  }
  
  return result;
}
async function findOne(_id) { 
  let result = null;
  try {
    let data = await userDao.findOne(_id)
    if (data !== null) {
      result = resultUtil(data, 0, 0, "成功");
    }
    else { 
      result = resultUtil(null, 0, -1, "登录失效，请重新登录");
    }
    
  }
  catch (e) { 
    result = resultUtil(null, 0,-1,"验证失败,请重新登录");
    console.log(e);
  }
  
  return result;
}

module.exports.getAllUsers = getAllUsers;
module.exports.list = list;
module.exports.deleteById = deleteById;
module.exports.add = add;
module.exports.login = login;
module.exports.findOne = findOne;